package com.unlcn.erp.hyc.interfaces.backend.util;


import cn.huiyunche.commons.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.*;

/**
 * @Author ：Ligl
 * @Date : 2017/5/11.
 */
public class HttpRequestUtil {


    private static final Logger LOGGER = LoggerFactory.getLogger(cn.huiyunche.commons.utils.HttpRequestUtil.class);

    //连接超时时间
    private static final int CONNECT_TIMEOUT = 10000;

    public static String sendHttpGet(final String url, /*final Map<String, Object> headerMap,*/ final Map<String, Object> paramsMap, final int socketTimeout) throws Exception {

        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet(url);
//        if (!Objects.equals(headerMap, null) || !Objects.equals(headerMap, "")) {
//            Iterator<Map.Entry<String, Object>> entries = headerMap.entrySet().iterator();
//            while (entries.hasNext()) {
//                Map.Entry<String, Object> entry = entries.next();
//                String value = Objects.equals(entry.getValue(), null) || Objects.equals(entry.getValue(), "")? "" : entry.getValue().toString();
//                httpGet.addHeader(entry.getKey(), value);
//            }
//        }
        RequestConfig.Builder builder = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(socketTimeout);
        httpGet.setConfig(builder.build());

        try {
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            return assemblyRetrunData(httpResponse);
        } catch (Exception e) {
            LOGGER.error("HttpRequestUtil error : {}", e);
            throw new BusinessException(e.getMessage());
        } finally {
            // 关闭连接,释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String sendHttpPost(final String url, final Map<String, Object> headerMap, final Map<String, Object> paramsMap, final int socketTimeout) throws Exception {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig.Builder builder = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(socketTimeout);
        httpPost.setConfig(builder.build());
        List<NameValuePair> formParams = new ArrayList<NameValuePair>();
        if (null != paramsMap && !paramsMap.isEmpty()) {
            Set<String> set = paramsMap.keySet();
            Iterator<String> iterator = set.iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                Object value = paramsMap.get(key);
                formParams.add(new BasicNameValuePair(key, null == value ? null : value.toString()));
            }
        }
        if (null != headerMap && !headerMap.isEmpty()) {
            Set<String> set = headerMap.keySet();
            Iterator<String> iterator = set.iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                String value = Objects.equals(headerMap.get(key), null) || Objects.equals(headerMap.get(key), "")? "" : headerMap.get(key).toString();
                httpPost.addHeader(key, value);
            }
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            return assemblyRetrunData(httpResponse);
        } catch (Exception e) {
            LOGGER.error("HttpRequestUtil error : {}", e);
            throw new BusinessException(e.getMessage());
        } finally {
            // 关闭连接,释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static String assemblyRetrunData(CloseableHttpResponse httpResponse) {
        StatusLine statusLine = httpResponse.getStatusLine();
        if (200 == statusLine.getStatusCode()) {
            try {
                HttpEntity entity = httpResponse.getEntity();
                String resultData = entity != null ? EntityUtils.toString(entity) : null;
                if (StringUtils.isBlank(resultData)) {
                    LOGGER.info("assemblyRetrunData is null");
                    throw new BusinessException("调用ERP无返回信息");
                }
                return resultData;
            } catch (IOException e) {
                LOGGER.error("assemblyRetrunData error : {}", e);
                e.printStackTrace();
            } finally {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    LOGGER.error("assemblyRetrunData error : {}", e);
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
